<template>
  <div class="contract_manage_detail">
    <el-dialog width="70%" class="WholeScroll" :visible.sync="formShow" @close="handleClickDeal('cancel')" v-dialog-drag :modal-append-to-body="false" :close-on-click-modal="false" append-to-body>
      <span slot="title">
        <i class="iconfont icon-hetongguanli2"></i>
        <span>{{ title }}</span>
      </span>
      <div class="WholeScroll" style="max-height: 650px; overflow: auto">
        <el-form :model="formBaseData" ref="formBaseData" :rules="formBaseRules">
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="基本信息" name="first">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="项目" prop="projectId" :label-width="formlabelWidth">
                    <el-select style="width: 100%" v-model="formBaseData.projectId" filterable placeholder="" :disabled="detailType === 'check'" @change="chooseProject(formBaseData.projectId)">
                      <el-option v-for="(item, i) in selectList.scopeProjects" :key="i" :label="item.proName" :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item label="合同分类" prop="type" :label-width="formlabelRightWidth">
                    <el-select style="width: 100%" v-model="formBaseData.type" filterable placeholder="" :disabled="detailType === 'check'" @change="changeSelectType()">
                      <el-option v-for="(item, i) in selectList.type" :key="i" :label="item.label" :value="item.value">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="12">
                  <el-form-item label="关联合同" :label-width="formlabelWidth">
                    <el-select style="width: 100%" v-model="formBaseData.oldContractId" filterable clearable placeholder="" :disabled="detailType === 'check'  || (!formBaseData.projectId ) " @change="chooseContract(formBaseData.oldContractId)">
                      <el-option v-for="(item, i) in selectList.contractList" :key="i" :label="item.title" :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>

              </el-row>

              <el-row>
                <el-col :span="24">
                  <el-form-item ref="select" label="土建标" prop="sectionIds" :label-width="formlabelRightWidth">
                    <el-select style="width: 100%" v-model="formBaseData.sectionIds" filterable placeholder="" :disabled="detailType === 'check' " @change="chooseSectionId()" multiple :multiple-limit="formBaseData.sectionMutiSelect?99999:1">
                      <el-option v-for="(item, i) in selectList.sectionList" :key="i" :label="item.code" :disabled="!item.selectable" :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="12">
                  <el-form-item label="合同编号" prop="number" :label-width="formlabelWidth">
                    <el-input class="contract_input" style="width: 100%" v-model="formBaseData.number" placeholder="" :disabled="detailType === 'check'  "></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item label="合同段名称" prop="numberName" :label-width="formlabelWidth">
                    <el-input class="contract_input" style="width: 100%" v-model="formBaseData.numberName" placeholder="" :disabled="detailType === 'check'  "></el-input>
                  </el-form-item>
                </el-col>

              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="合同名称" prop="title" :label-width="formlabelRightWidth">
                    <el-input style="width: 100%" v-model="formBaseData.title" placeholder="" :disabled="detailType === 'check' "></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <!--              <el-row>
                <el-col :span="12">
                  <el-form-item
                    label="合同总金额"
                    prop="amount"
                    :label-width="formlabelWidth"
                  >
                    <el-input
                      class="contract_input"
                      style="width: 100%"
                      v-model="formBaseData.amount"
                      @blur="blurInputEvent"
                      oninput="value=value.replace(/[^0-9.]/g,'')"
                      placeholder=""
                      :disabled="detailType === 'check' "
                    >
                      <template slot="append">万元</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label="变更后合同总金额"
                    prop="changeAmount"
                    :label-width="formlabelWidth"
                  >
                    <el-input
                      class="contract_input"
                      style="width: 100%"
                      v-model="formBaseData.changeAmount"
                      @blur="blurInputEvent"
                      oninput="value=value.replace(/[^0-9.]/g,'')"
                      placeholder=""
                      :disabled="detailType === 'check' "
                    >
                      <template slot="append">万元</template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>-->

              <el-row>
                <el-col :span="12">
                  <el-form-item label="是否联合体" prop="chooseIsConsortium" :label-width="formlabelWidth">
                    <el-radio-group v-model="formBaseData.chooseIsConsortium" size="small" @change="changeRadio">
                      <el-radio :disabled="detailType !== 'build'" label="1">不是联合体</el-radio>
                      <el-radio :disabled="detailType !== 'build'" label="2">是联合体</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>

                <el-col :span="12" v-if="formBaseData.chooseIsConsortium == 2">
                  <el-form-item label="联合体单位数" prop="consortiumNumber" :label-width="formlabelWidth">
                    <el-select style="width: 100%" v-model="formBaseData.consortiumNumber" @change="changeConNumber" :disabled="detailType === 'check' " filterable placeholder="">
                      <el-option v-for="(item, i) in selectList.consortiumNumList" :key="i" :label="item.name" :value="item.value">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <div v-if="formBaseData.chooseIsConsortium == 1">
                <el-row>
                  <el-col :span="24">
                    <el-form-item prop="secondParty" :label=secondCompanylabel :label-width="formlabelWidth">
                      <el-select style="width: 100%" v-model="formBaseData.secondParty" @change="changeSecondParty" :disabled="detailType === 'check' " filterable placeholder="">
                        <el-option v-for="(item, i) in selectList.companyListFiltered" :key="i" :label="item.fullname" :value="item.id">
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>

                </el-row>

                <el-row>
                  <el-col :span="24">
                    <!--            <el-form-item
                      prop="memberUids"
                      :label=secondCompanyPersonlabel
                      :label-width="formlabelWidth"
                    >
                      <el-select
                        style="width: 100%"
                        v-model="formBaseData.memberUids"
                        @change="$forceUpdate()"
                        filterable
                        placeholder=""
                        :disabled="detailType === 'check' || !formBaseData.secondParty"
                        multiple
                      >
                        <el-option
                          v-for="(item, i) in selectList.secondPartUserOpts"
                          :key="i"
                          :label="item.name"
                          :value="item.id"
                        >
                        </el-option>
                      </el-select>
                    </el-form-item>-->

                    <el-form-item :label=secondCompanyPersonlabel :label-width="formlabelWidth">
                      <cmsPopoverTree :defaultProps="defaultProps" ref="cmsPopoverTree" :data="linkUserOpts" :selectVal="checkedLinkUsers" type="multi" @addMulTag="addMulTag" :defaultIds="defaultIds" @delTag="delTag" @addTag="addTag" :disabled="detailType === 'check' || !formBaseData.secondParty" />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="12">
                    <el-form-item label="施工期合同金额" prop="constructionPeriodMoney" :label-width="formlabelWidth">
                      <el-input class="contract_input" style="width: 100%" @blur="blurInputEvent" type="number" @keydown.native="$publicJs.changeInputLimit" v-model="formBaseData.constructionPeriodMoney" placeholder="" :disabled="detailType === 'check' ">
                        <template slot="append">万元</template>
                      </el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="变更增减金额" prop="modifyConstructionPeriodMoney" :label-width="formlabelWidth">
                      <el-input class="contract_input" style="width: 100%" v-model="formBaseData.modifyConstructionPeriodMoney" @blur="blurInputEvent" type="number" @keydown.native="$publicJs.changeInputLimit" placeholder="" :disabled="detailType === 'check' ">
                        <template slot="append">万元</template>
                      </el-input>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="12">
                    <el-form-item label="缺陷责任期合同金额" prop="defectsPeriodMoney" :label-width="formlabelWidth">
                      <el-input class="contract_input" style="width: 100%" v-model="formBaseData.defectsPeriodMoney" @blur="blurInputEvent" type="number" @keydown.native="$publicJs.changeInputLimit" placeholder="" :disabled="detailType === 'check' ">
                        <template slot="append">万元</template>
                      </el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="变更增减金额" prop="modifyDefectsPeriodMoney" :label-width="formlabelWidth">
                      <el-input class="contract_input" style="width: 100%" v-model="formBaseData.modifyDefectsPeriodMoney" @blur="blurInputEvent" type="number" @keydown.native="$publicJs.changeInputLimit" placeholder="" :disabled="detailType === 'check' ">
                        <template slot="append">万元</template>
                      </el-input>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="12">
                    <el-form-item label="暂列金额" prop="provisionalSum" :label-width="formlabelWidth">
                      <el-input class="contract_input" style="width: 100%" v-model="formBaseData.provisionalSum" @blur="blurInputEvent" type="number" @keydown.native="$publicJs.changeInputLimit" placeholder="" :disabled="detailType === 'check' ">
                        <template slot="append">万元</template>
                      </el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="变更增减金额" prop="modifyProvisionalSum" :label-width="formlabelWidth">
                      <el-input class="contract_input" style="width: 100%" v-model="formBaseData.modifyProvisionalSum" @blur="blurInputEvent" type="number" @keydown.native="$publicJs.changeInputLimit" placeholder="" :disabled="detailType === 'check' ">
                        <template slot="append">万元</template>
                      </el-input>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="12">
                    <el-form-item label="合同负责人(乙方)" prop="principalOfSecondParty" :label-width="formlabelRightWidth">
                      <el-input style="width: 100%" v-model="formBaseData.principalOfSecondParty" placeholder="" :disabled="detailType === 'check' "></el-input>
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item label="联系方式" prop="principalOfSecondPartyMobile" :label-width="formlabelRightWidth">
                      <el-input style="width: 100%" v-model="formBaseData.principalOfSecondPartyMobile" placeholder="" :disabled="detailType === 'check' "></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="12">
                    <el-form-item label="收款账户" prop="payedCompanyName" :label-width="formlabelRightWidth">
                      <el-input style="width: 100%" v-model="formBaseData.payedCompanyName" placeholder="" :disabled="detailType === 'check'  "></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="开户银行" prop="depositBank" :label-width="formlabelRightWidth">
                      <el-input style="width: 100%" v-model="formBaseData.depositBank" placeholder="" :disabled="detailType === 'check'  "></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="12">
                    <el-form-item label="账号" prop="bankAccount" :label-width="formlabelRightWidth">
                      <el-input style="width: 100%" v-model="formBaseData.bankAccount" placeholder="" :disabled="detailType === 'check'  "></el-input>
                    </el-form-item>
                  </el-col>

                </el-row>

                <el-row>
                  <el-col :span="24">
                    <el-col :span="12">
                      <el-form-item label="合同签订日期" prop="orderDate" :label-width="formlabelWidth">
                        <el-date-picker style="width: 100%" v-model="formBaseData.orderDate" type="date" format="yyyy-MM-dd" placeholder="选择合同签订日期" :disabled="detailType === 'check' " value-format="yyyy-MM-dd">
                        </el-date-picker>
                      </el-form-item>
                    </el-col>

                    <el-col :span="12">
                      <el-form-item label="费率(%)" prop="rate" :label-width="formlabelWidth">
                        <el-input style="width: 100%" v-model="formBaseData.rate" type="number" placeholder="" @blur="blurInputEvent_feilv" :disabled="detailType === 'check'"></el-input>
                      </el-form-item>
                    </el-col>
                  </el-col>

                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="起始桩号" prop="initialPileNo" :label-width="formlabelWidth">
                      <el-input style="width: 100%" v-model="formBaseData.initialPileNo" placeholder="" :disabled="detailType === 'check'"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="结束桩号" prop="overPileNo" :label-width="formlabelRightWidth">
                      <el-input style="width: 100%" v-model="formBaseData.overPileNo" placeholder="" :disabled="detailType === 'check'"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="合同长度" prop="length" :label-width="formlabelWidth">
                      <el-input style="width: 100%" v-model="formBaseData.length" placeholder="" :disabled="detailType === 'check'" @blur="onNewNumber('length')">
                        <template slot="append">KM</template>
                      </el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="合同工期" prop="duration" :label-width="formlabelRightWidth">
                      <el-input style="width: 100%" v-model="formBaseData.duration" placeholder="" :disabled="detailType === 'check'">
                        <template slot="append">天</template>
                      </el-input>
                    </el-form-item>
                  </el-col>
                </el-row>

              </div>
              <el-tabs v-if="formBaseData.chooseIsConsortium == 2" v-model="consortiumActive" type="card">
                <el-tab-pane v-for="(item,index) in formBaseData.consortiumGroup" :key="index" :label="item.label" :name="item.value">
                  <el-row>
                    <el-col :span="24">
                      <el-form-item :prop="'consortiumGroup.'+index + '.secondParty'" :rules="formBaseRules.secondParty" :label="chooseConLabel(item.label)" :label-width="formlabelWidth">
                        <el-select style="width: 100%" v-model="item.secondParty" @change="val=>changeSecondPartyConsortium(val,index)" :disabled="detailType === 'check' " filterable placeholder="">
                          <el-option v-for="(item, i) in selectList.companyListFiltered" :key="i" :label="item.fullname" :disabled="!item.selectable" :value="item.id">
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>

                  </el-row>
                  <el-row>
                    <el-col :span="24">
                      <!--<el-form-item
                        :prop="'consortiumGroup.'+index + '.memberUids'"
                        :rules="formBaseRules.memberUids"
                        :label=secondCompanyPersonlabel
                        :label-width="formlabelWidth"
                      >
                        <el-select
                          style="width: 100%"
                          v-model="item.memberUids"
                          filterable
                          filterable
                          placeholder=""
                          :disabled="detailType === 'check' || !item.secondParty"
                          multiple
                        >
                          <el-option
                            v-for="(item, i) in item.secondPartUserOpts"
                            :key="i"
                            :label="item.name"
                            :value="item.id"
                          >
                          </el-option>
                        </el-select>
                      </el-form-item>-->

                      <el-form-item :label=secondCompanyPersonlabel :label-width="formlabelWidth">
                        <cmsPopoverTree :defaultProps="defaultProps" ref="cmsPopoverTree" :data="item.linkUserOpts" :selectVal="item.checkedLinkUsers" type="multi" @addMulTag="val=>addMulTagItem(val,index)" :defaultIds="defaultIdsItem" @delTag="val=>delTagItem(val,index)" @addTag="val=>addTagItem(val,index)" :disabled="detailType === 'check' || !item.secondParty" />
                      </el-form-item>

                    </el-col>

                  </el-row>

                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="施工期合同金额" :prop="'consortiumGroup.'+index + '.constructionPeriodMoney'" :label-width="formlabelWidth" :rules="formBaseRules.constructionPeriodMoney">
                        <el-input class="contract_input" style="width: 100%" v-model="item.constructionPeriodMoney" @keyup.native="newUpNumber" @keydown.native="newUpNumber" placeholder="" :disabled="detailType === 'check' ">
                          <template slot="append">万元</template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="变更增减金额" :prop="'consortiumGroup.'+index + '.modifyConstructionPeriodMoney'" :label-width="formlabelWidth" :rules="formBaseRules.modifyConstructionPeriodMoney">
                        <el-input class="contract_input" style="width: 100%" v-model="item.modifyConstructionPeriodMoney" @keyup.native="newUpNumber" @keydown.native="newUpNumber" placeholder="" :disabled="detailType === 'check' ">
                          <template slot="append">万元</template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>

                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="缺陷责任期合同金额" :prop="'consortiumGroup.'+index + '.defectsPeriodMoney'" :label-width="formlabelWidth" :rules="formBaseRules.defectsPeriodMoney">
                        <el-input class="contract_input" style="width: 100%" v-model="item.defectsPeriodMoney" @keyup.native="newUpNumber" @keydown.native="newUpNumber" placeholder="" :disabled="detailType === 'check' ">
                          <template slot="append">万元</template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="变更增减金额" :prop="'consortiumGroup.'+index + '.modifyDefectsPeriodMoney'" :label-width="formlabelWidth" :rules="formBaseRules.modifyDefectsPeriodMoney">
                        <el-input class="contract_input" style="width: 100%" v-model="item.modifyDefectsPeriodMoney" @keyup.native="newUpNumber" @keydown.native="newUpNumber" placeholder="" :disabled="detailType === 'check' ">
                          <template slot="append">万元</template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>

                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="暂列金额" :prop="'consortiumGroup.'+index + '.provisionalSum'" :label-width="formlabelWidth" :rules="formBaseRules.provisionalSum">
                        <el-input class="contract_input" style="width: 100%" v-model="item.provisionalSum" @keyup.native="newUpNumber" @keydown.native="newUpNumber" placeholder="" :disabled="detailType === 'check' ">
                          <template slot="append">万元</template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="变更增减金额" :prop="'consortiumGroup.'+index + '.modifyProvisionalSum'" :label-width="formlabelWidth" :rules="formBaseRules.modifyProvisionalSum">
                        <el-input class="contract_input" style="width: 100%" v-model="item.modifyProvisionalSum" @keyup.native="newUpNumber" @keydown.native="newUpNumber" placeholder="" :disabled="detailType === 'check' ">
                          <template slot="append">万元</template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>

                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="合同负责人(乙方)" :prop="'consortiumGroup.'+index + '.principalOfSecondParty'" :label-width="formlabelRightWidth" :rules="formBaseRules.principalOfSecondParty">
                        <el-input style="width: 100%" v-model="item.principalOfSecondParty" placeholder="" :disabled="detailType === 'check' "></el-input>
                      </el-form-item>
                    </el-col>

                    <el-col :span="12">
                      <el-form-item label="联系方式" :prop="'consortiumGroup.'+index + '.principalOfSecondPartyMobile'" :rules="formBaseRules.principalOfSecondPartyMobile" :label-width="formlabelRightWidth">
                        <el-input style="width: 100%" v-model="item.principalOfSecondPartyMobile" placeholder="" :disabled="detailType === 'check' "></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="收款账户" :prop="'consortiumGroup.'+index + '.payedCompanyName'" :rules="formBaseRules.payedCompanyName" :label-width="formlabelRightWidth">
                        <el-input style="width: 100%" v-model="item.payedCompanyName" placeholder="" :disabled="detailType === 'check'  "></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="开户银行" :prop="'consortiumGroup.'+index + '.depositBank'" :rules="formBaseRules.depositBank" :label-width="formlabelRightWidth">
                        <el-input style="width: 100%" v-model="item.depositBank" placeholder="" :disabled="detailType === 'check'  "></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>

                  <el-row>

                    <el-col :span="12">
                      <el-form-item label="账号" :prop="'consortiumGroup.'+index + '.bankAccount'" :rules="formBaseRules.bankAccount" :label-width="formlabelRightWidth">
                        <el-input style="width: 100%" v-model="item.bankAccount" placeholder="" :disabled="detailType === 'check'  "></el-input>
                      </el-form-item>
                    </el-col>

                  </el-row>

                  <el-row>
                    <el-col :span="24">
                      <el-col :span="12">
                        <el-form-item label="合同签订日期" prop="orderDate" :label-width="formlabelWidth">
                          <el-date-picker style="width: 100%" v-model="item.orderDate" type="date" format="yyyy-MM-dd" placeholder="选择合同签订日期" :disabled="detailType === 'check' " value-format="yyyy-MM-dd">
                          </el-date-picker>
                        </el-form-item>
                      </el-col>

                      <el-col :span="12">
                        <el-form-item label="费率(%)" prop="rate" :label-width="formlabelWidth">
                          <el-input style="width: 100%" v-model="item.rate" type="number" placeholder="" @blur="blurInputEvent_feilv(item.rate)" :disabled="detailType === 'check'"></el-input>
                        </el-form-item>
                      </el-col>
                    </el-col>

                  </el-row>
                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="起始桩号" prop="initialPileNo" :label-width="formlabelWidth">
                        <el-input style="width: 100%" v-model="item.initialPileNo" placeholder="" :disabled="detailType === 'check'"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="结束桩号" prop="overPileNo" :label-width="formlabelRightWidth">
                        <el-input style="width: 100%" v-model="item.overPileNo" placeholder="" :disabled="detailType === 'check'"></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="合同长度" prop="length" :label-width="formlabelWidth">
                        <el-input style="width: 100%" v-model="item.length" placeholder="" :disabled="detailType === 'check'">
                          <template slot="append">KM</template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="合同工期" prop="duration" :label-width="formlabelRightWidth">
                        <el-input style="width: 100%" v-model="item.duration" placeholder="" :disabled="detailType === 'check'" @blur="onNewNumber('duration',0)">
                          <template slot="append">天</template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>

                </el-tab-pane>
              </el-tabs>

              <el-col :span="24">
                <div class="formTitle">附件</div>
                <cmsFileTable ref="cmsFileTable" :buildUnitTable="buildUnitTable" :fileSystem="fileSystem" :detailId="detailId" :detailType="detailType" :buttonDelShow="buttonDelShow" :showNone="showNone" :buttonCheckShow="buttonCheckShow" :buttonUploadShow="buttonUploadShow" @change="tableChange">
                </cmsFileTable>
              </el-col>
            </el-tab-pane>

          </el-tabs>
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer">
        <!--api操作按钮 除去上报-->
        <!--新建和编辑的暂存上报-->
        <template v-if="detailType === 'build' || detailType === 'edit'">
          <el-button size="small" type="primary" :loading="isLoading" @click="handleClickDeal('submit', { flag: 1 })"><i class="iconfont icon-icon_save"></i> 确 定
          </el-button>
        </template>
        <el-button size="small" @click="handleClickDeal('cancel')"><i class="iconfont icon-icon_cancel"></i> 取 消
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
import cmsPopoverTree from '@/views/components/cmsPopoverTree.vue'
import crudProject from '@/api/buss/project'
import crudDict from '@/api/system/dict'
import msgUtil from '@/utils/msgUtil'
import projectSectionInfo from '@/api/buss/common'
import mainline from '@/api/buss/mainlineContract'
import dept from '@/api/system/dept'
import { getConsortiumUnitNum, getOne } from "../../../../api/buss/mainlineContract";

export default {
  name: 'superviseContract-detail',
  components: {
    cmsPopoverTree,

  },
  props: {
    postDetail: {
      type: Object,
      default: {
        show: false,
        type: 'build',
        params: {}
      }
    }
  },
  watch: {
    postDetail(value) {
      console.log(value)
      // 显示详情弹窗
      this.formShow = value.show
      // 初始化窗口参数
      this.activeName = 'first'
      // 详情类型
      this.detailType = value.type

      this.buildUnitTable = [
        {
          stuffName: '合同文本',
          part: "partOne",
          file: [{ realName: '' }],
          isNeed: false,
          loading: false,
          isMulti: true
        },
        {
          stuffName: '其他',
          file: [{ realName: '' }],
          part: "other",
          isNeed: false,
          loading: false,
          isMulti: true
        },
      ],


        this.detailId = value.detailId ? value.detailId : '';

      this.initData()

      if (this.detailType !== 'build') {
        // 获取详情请求

        this.getAllCompany().then(item => {
          this.getDetail()
        })
        if (this.detailType == "check") {
          this.title = "查看合同"
        }
        if (this.detailType == "edit") {
          this.title = "编辑合同"
        }
      }
      if (this.detailType === 'build') {
        this.title = "新增合同"
        // 获取编号
        this.getScopeProjects("")
        this.getAllCompany()
      }


    },
    //判断是否联合体  变量监听
    'formBaseData.chooseIsConsortium': {
      handler(val) {
        console.log(val)
        if (val == 2) {
          if (this.detailType == 'build') {
            //如果选择是联合体，清空原对象
            this.changeConNumber(val)
          }


        } else {
          //如果切换到 不是联合体清空原数组
        }
      },
      deep: true
    }
  },
  data() {
    return {
      linkUsers: {},
      ownerRepresentativeUsers: {},
      ownerRepresentativeUserOpts: [],
      linkUserOpts: [],
      checkedLinkUsers: [],
      defaultIds: [],
      defaultIdsItem: [],
      defaultProps: {
        children: 'children',
        label: 'name',
      },
      MContractType: [],
      secondCompanylabel: '选择监理单位',
      secondCompanyPersonlabel: '监理单位履约人员',
      isLoading: false,
      detailType: 'build', // 详情类型 build新建 check不可编辑查看 edit编辑
      detailId: '', // 当前详情的id
      detailActions: [], // 当前详情的操作项
      formShow: false, // 表单展示
      formlabelWidth: '150px', // 表单左侧标题宽度
      formlabelRightWidth: '150px', // 表单左侧标题宽度
      formlabelWidth2: '120px', // 表单左侧标题宽度
      title: '新增合同',
      activeName: 'first',
      consortiumActive: '1',
      // 所有下拉框列表的集合
      selectList: {
        //所有合同
        contractList: [],
        consortiumNumList: [],
        //类型
        type: [
          {
            label: '全部',
            value: '0'
          }
        ], // 关联标段
        sectionList: [
          {
            label: '全部',
            value: '0'
          }
        ], // 阶段
        //公司列表
        companyList: [],
        //  公司列表根据类型过滤后的结果
        companyListFiltered: [],
        //  可以选择的项目列表
        scopeProjects: [],
        file: [], // 文件
        //  标段负责人选择项
        secondPartUserOpts: [],
        //  甲方标段管理人选择项
        firstPartUserOpts: [],
      },
      // 表单基本信息内容
      consortiumGroupCopy: [],
      formBaseData: {
        chooseIsConsortium: '1',
        consortiumGroup: [],
        oldContractId: '',
        oldContractIdFlag: false,
        consortiumNumber: '',
        memberUids: [],
        secondPartyRelation: true,
        // enableSectionSelection:false,
        sectionIds: '',
        contractManaged: false,
        sectionMutiSelect: true,
        //合同信息
        number: '',
        numberName: '',
        title: '',
        amount: '',
        changeAmount: '',
        type: '',
        secondParty: '',
        rate: '',
        initialPileNo: '',
        length: '',
        principalOfSecondParty: '',
        principalOfSecondPartyMobile: '',
        payedCompanyName: '',
        depositBank: '',
        bankAccount: '',
        contractManageDeptName: '',
        overPileNo: '',
        duration: '',
        orderDate: '',
        modifyProvisionalSum: '',
        provisionalSum: '',
        constructionPeriodMoney: '',
        modifyConstructionPeriodMoney: '',
        defectsPeriodMoney: '',
        modifyDefectsPeriodMoney: '',
      },
      // 表单基本信息验证
      formBaseRules: {

        oldContractId: [{
          required: true, message: '请选择关联合同', trigger: 'blur'
        }],
        modifyProvisionalSum: [{ required: true, message: '请输入暂列金变更增减金额', trigger: 'blur' }],
        provisionalSum: [{ required: true, message: '请输入暂列金', trigger: 'blur' }],
        constructionPeriodMoney: [{ required: true, message: '请输入施工期合同金额', trigger: 'blur' }],
        modifyConstructionPeriodMoney: [{ required: true, message: '请输入施工期合同变更增减金额', trigger: 'blur' }],
        defectsPeriodMoney: [{ required: true, message: '请输入缺陷责任期合同金额', trigger: 'blur' }],
        modifyDefectsPeriodMoney: [{ required: true, message: '请输入缺陷责任期合同-变更增减金额', trigger: 'blur' }],

        // payedCompanyName:[{required: true, message:'请输入收款账户', trigger: 'blur'}],
        // depositBank:[{required: true, message:'请输入开户银行', trigger: 'blur'}],
        // bankAccount:[{required: true, message:'请输入账号', trigger: 'blur'}],
        /*memberUids:[{required: true, message:'请选择履约人员', trigger: 'blur'}],*/
        consortiumNumber: [{ required: true, message: '请选择联合体单位数', trigger: 'blur' }],
        projectId: [{ required: true, message: '请选择项目', trigger: 'blur' }],

        secondParty: [{ required: true, message: '请选择乙方单位', trigger: 'blur' }],
        sectionIds: [{ required: true, message: '请选择标段', trigger: 'blur' }],

        number: [
          { required: true, message: '请输入' + '合同编号', trigger: 'blur' }
        ],
        numberName: [
          { required: true, message: '请输入' + '合同段编号', trigger: 'blur' }
        ],
        chooseIsConsortium: [
          { required: true, message: '请选择' + '是否联合体', trigger: 'blur' }
        ],
        title: [
          { required: true, message: '请输入' + '合同名称', trigger: 'blur' }
        ],
        amount: [
          { required: true, message: '请输入' + '合同总金额', trigger: 'blur' }
        ],
        changeAmount: [
          { required: true, message: '请输入' + '变更后合同总金额', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择' + '合同类型', trigger: 'change' }
        ],

        secondParty: [
          {
            required: true,
            message: '请选择' + '合同签订单位(乙方)',
            trigger: 'blur'
          }
        ],
        principalOfSecondParty: [
          {
            required: true,
            message: '请输入' + '合同负责人(乙方)',
            trigger: 'blur'
          }
        ],


        // principalOfSecondPartyMobile: [
        //   {
        //     required: true,
        //     message: '请输入' + '联系方式',
        //     trigger: 'blur'
        //   }
        // ],

        // scopeProjects: [
        //     {required: true, message: '请选择' + '所属项目', trigger: 'change'}
        // ],
        contractManaged: [
          {
            required: true,
            message: '请选择' + '乙方单位是否为总承包单位',
            trigger: 'change'
          }
        ],
        contractManageDeptName: [
          {
            required: true,
            message: '请填写' + '乙方总承包部名称',
            trigger: 'change'
          }
        ],
        /* memberUids: [
           {
             required: true,
             message: '请选择' + '乙方单位参与人',
             trigger: 'blur'
           }
         ],*/

      },
      //  允许标段选择项
      enableSectionSelection: false,
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      //  是否需要出现标段
      enableSection: false,
      //  是否需要选择是否总承包
      enableWhetherManageSelection: false,
      showList: false,
      buildUnitTable: [
        {
          stuffName: '合同文本',
          part: "partOne",
          file: [{ realName: '' }],
          isNeed: false,
          loading: false,
          isMulti: true
        },
        {
          stuffName: '其他',
          file: [{ realName: '' }],
          part: "other",
          isNeed: false,
          loading: false,
          isMulti: true
        },
      ],
      fileSystem: {
        attachId: {
          partOne: '',
          partTwo: '',
          partThree: '',
          partFour: '',
          other: '',
        },
        sys: 'buss',
        module: 'superviseContract',
        entityClass: 'superviseContract',
        viewByAnon: true,
        longLife: false,
        part: {
          partOne: 'partOne',
          partTwo: 'partTwo',
          partThree: 'partThree',
          partFour: 'partFour',
          other: "other",
        },
      },

    }
  },

  filters: {
    moneyFilter(value) {
      try {
        let before = value.toFixed(2)
        before = before.toString()
        let num = before.split('.')[0]
        let numSmall = before.split('.')[1]
        let result = [],
          counter = 0
        num = (num || 0).toString().split('')
        for (let i = num.length - 1; i >= 0; i--) {
          counter++
          result.unshift(num[i])
          if (!(counter % 3) && i != 0) {
            result.unshift(',')
          }
        }
        let after =
          numSmall === undefined
            ? result.join('')
            : result.join('') + '.' + numSmall
        return after
      } catch (e) {
        return ''
      }
    }
  },
  created() {

  },
  methods: {
    onNewNumber(str, num) {
      let digit = 2
      if (num !== undefined) { digit = num }
      if (Number(this.formBaseData[str])) {
        this.formBaseData[str] = Number(this.formBaseData[str]).toFixed(digit)
      } else {
        this.$set(this.formBaseData, str, '')
      }
    },
    getLinkUserOpts(compId) {
      this.linkUserOpts = []
      this.checkedLinkUsers = []
      crudProject.getlinkUsersDept(compId).then(res => {
        if (res.status === 1) {
          let linkUserOpts = res.data;
          this.linkUserOpts = linkUserOpts;
          let ownerRepresentativeUserOpts = res.data;
          this.ownerRepresentativeUserOpts = ownerRepresentativeUserOpts;
          console.log(res.data, '俏丽吗++++++++++++++++++++++++++')
          this.collectDeptUserById(linkUserOpts);
          this.collectDeptUserCompById(ownerRepresentativeUserOpts);
          this.$forceUpdate();
        } else {
          //this.$messageError(res.data.message)
          msgUtil.error2(res.data.message)
        }
      }).catch(res => {
        console.log('请求出现错误', res);
        msgUtil.error2('获取部门用户列表失败!')
      })
    },

    getLinkUserOptss(compId) {
      return crudProject.getlinkUsersDept(compId).then(res => {
        if (res.status === 1) {
          let linkUserOpts = res.data;
          //if(this.detailType != 'edit'){
          this.linkUserOpts = linkUserOpts;
          //}
          let ownerRepresentativeUserOpts = res.data;
          this.ownerRepresentativeUserOpts = ownerRepresentativeUserOpts;
          console.log(res.data, '俏丽吗++++++++++++++++++++++++++')
          this.collectDeptUserById(linkUserOpts);
          this.collectDeptUserCompById(ownerRepresentativeUserOpts);
          return new Promise(reslove => {
            reslove(res)
          })
          this.$forceUpdate();
        } else {
          //this.$messageError(res.data.message)
          msgUtil.error2(res.data.message)
        }
      }).catch(res => {
        console.log('请求出现错误', res);
        msgUtil.error2('获取部门用户列表失败!')
      })
    },

    getLinkUserOptsConsortium(index) {
      let chooseId = this.formBaseData.consortiumGroup[index].secondParty
      this.formBaseData.consortiumGroup[index].linkUserOpts = []
      this.formBaseData.consortiumGroup[index].checkedLinkUsers = []
      crudProject.getlinkUsersDept(chooseId).then(res => {
        if (res.status === 1) {
          let linkUserOpts = res.data;
          this.formBaseData.consortiumGroup[index].linkUserOpts = linkUserOpts;
          let ownerRepresentativeUserOpts = res.data;
          this.ownerRepresentativeUserOpts = ownerRepresentativeUserOpts;
          console.log(res.data, '俏丽吗++++++++++++++++++++++++++')
          this.collectDeptUserById(linkUserOpts);
          this.collectDeptUserCompById(ownerRepresentativeUserOpts);
          this.$forceUpdate();
        } else {
          //this.$messageError(res.data.message)
          msgUtil.error2(res.data.message)
        }
      }).catch(res => {
        console.log('请求出现错误', res);
        msgUtil.error2('获取部门用户列表失败!')
      })
    },

    getLinkUserOptssConsortium(index) {
      let chooseId = this.formBaseData.consortiumGroup[index].secondParty
      this.formBaseData.consortiumGroup[index].linkUserOpts = []
      this.formBaseData.consortiumGroup[index].checkedLinkUsers = []
      return crudProject.getlinkUsersDept(chooseId).then(res => {
        if (res.status === 1) {
          let linkUserOpts = res.data;
          //if(this.detailType != 'edit'){
          this.formBaseData.consortiumGroup[index].linkUserOpts = linkUserOpts;
          //}
          let ownerRepresentativeUserOpts = res.data;
          this.ownerRepresentativeUserOpts = ownerRepresentativeUserOpts;
          console.log(res.data, '俏丽吗++++++++++++++++++++++++++')
          this.collectDeptUserById(linkUserOpts);
          this.collectDeptUserCompById(ownerRepresentativeUserOpts);
          return new Promise(reslove => {
            reslove(res)
          })
          this.$forceUpdate();
        } else {
          //this.$messageError(res.data.message)
          msgUtil.error2(res.data.message)
        }
      }).catch(res => {
        console.log('请求出现错误', res);
        msgUtil.error2('获取部门用户列表失败!')
      })
    },



    collectDeptUserById(linkUserOpts) {
      for (let i = 0; i < linkUserOpts.length; i++) {
        let user = linkUserOpts[i]
        let id = user.id
        let children = user.children
        this.linkUsers[id] = user
        if (children && children.length > 0) {
          this.collectDeptUserById(children)
        }
      }
    },

    collectDeptUserCompById(ownerRepresentativeUserOpts) {
      for (let i = 0; i < ownerRepresentativeUserOpts.length; i++) {
        let user = ownerRepresentativeUserOpts[i]
        let id = user.id
        let children = user.children

        this.ownerRepresentativeUsers[id] = user
        if (children && children.length > 0) {
          this.collectDeptUserCompById(children)
        }
      }
    },

    /**
     *  -----@addMulTag="addMulTag"
     * 多选增加--多选模式使用
     * @param val
     */
    addMulTag(val) {
      console.log(val)
      // this.checkedLinkUsers.splice(0, this.checkedLinkUsers.length)
      this.checkedLinkUsers = []
      val.forEach((item) => {
        this.checkedLinkUsers.push(item)
      })
      this.$forceUpdate()
    },
    /**
     * 删除会签部门人
     */
    delTag(val) {
      this.checkedLinkUsers.splice(val, 1)

      this.$forceUpdate()
      this.$refs.cmsPopoverTree.updateTree()
      this.$refs.cmsPopoverTree.$forceUpdate()
    },
    /**
     * 增加会签人
     * @param val
     */
    addTag(val) {
      this.checkedLinkUsers.push(val)
      this.$refs.cmsPopoverTree.updateTree()
      this.$refs.cmsPopoverTree.$forceUpdate()
      this.$forceUpdate()
    },


    /**
     *  -----@addMulTag="addMulTag"
     * 多选增加--多选模式使用
     * @param val
     */
    addMulTagItem(val, index) {
      console.log(val)
      // this.checkedLinkUsers.splice(0, this.checkedLinkUsers.length)
      this.formBaseData.consortiumGroup[index].checkedLinkUsers = []
      val.forEach((item) => {
        this.formBaseData.consortiumGroup[index].checkedLinkUsers.push(item)
      })
      this.$forceUpdate()
    },
    /**
     * 删除会签部门人
     */
    delTagItem(val, index) {
      this.formBaseData.consortiumGroup[index].checkedLinkUsers.splice(val, 1)
      this.$forceUpdate()
      this.$refs.cmsPopoverTree[index].updateTree()
      this.$refs.cmsPopoverTree[index].$forceUpdate()
    },
    /**
     * 增加会签人
     * @param val
     */
    addTagItem(val, index) {
      this.formBaseData.consortiumGroup[index].checkedLinkUsers.push(val)
      this.$refs.cmsPopoverTree[index].updateTree()
      this.$refs.cmsPopoverTree[index].$forceUpdate()
      this.$forceUpdate()
    },
    newUpNumber() {
      var obj = event.target;
      var t = obj.value.charAt(0);
      obj.value = obj.value.replace(".", "$#$")//把第一个字符'.'替换成'$#$'
        .replace(/\./g, "")//把其余的字符'.'替换为空
        .replace("$#$", ".")//把字符'$#$'替换回原来的'.'
        .replace(/[^\d.]/g, "")//只能输入数字和'.'
        .replace(/^\./g, "")//不能以'.'开头
        .replace(/([0-9]+\.[0-9]{2})[0-9]*/, "$1")//只保留2位小数
      if (t == '-') {
        obj.value = '-' + obj.value;
      }
    },


    initData() {
      this.typeOptions = []
      this.companyTree = []
      this.selectList.type = []
      this.selectList.consortiumNumList = []
      crudDict.getByCode('MContractType').then(res => {
        if (res.code === 200) {
          var data = res.data;
          this.MContractType = res.data
          for (var i in data) {
            if (data[i].tips.indexOf("监理类") != -1) {
              this.selectList.type.push({ 'value': data[i].id, 'label': data[i].name });
              if (data[i].id == '402881ac7e0de9dd017e761cae552afe') {
                this.formBaseData.type = '402881ac7e0de9dd017e761cae552afe'
              }
            }
          }
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(() => {
        msgUtil.error2("获取问题归属失败")
      })


      mainline.getConsortiumUnitNum().then(res => {
        if (res.status === 1) {
          this.selectList.consortiumNumList = res.data;
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(() => {
        msgUtil.error2("获取问题归属失败")
      })

    },

    getAllCompany() {
      return dept.listForSys("").then(res => {
        this.selectList.companyList = []
        if (res.code === 200) {
          this.selectList.companyList = res.data
          return new Promise(reslove => {
            reslove(res)
          })

        } else {
          msgUtil.error2(res.data.message)
        }
      })
    },


    getScopeProjects(id) {
      mainline.getScopeProjects(id).then(res => {
        if (res.status === 1) {
          this.selectList.scopeProjects = res.data
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(res => {
        console.log('请求出现错误', res);
        msgUtil.error2('获取项目列表失败!')
      })
    },


    getRelatedContractList(projectId, typeName) {
      mainline.getRelatedContractList(projectId, typeName).then(res => {
        if (res.status === 1) {
          this.selectList.contractList = res.data
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(res => {
        console.log('请求出现错误', res);
        msgUtil.error2('获取关联合同列表失败!')
      })
    },

    getProjectSection(projectId) {
      mainline.getProjectSection(projectId, this.detailId, this.formBaseData.type).then(res => {
        if (res.status === 1) {
          this.selectList.sectionList = res.data
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(res => {
        console.log('请求出现错误', res);
        msgUtil.error2('获取标段列表失败!')
      })
    },

    //选择项目
    chooseProject(projectId) {
      this.formBaseData.oldContractId = ''
      this.formBaseData.number = ''
      this.formBaseData.numberName = ''
      this.secondPartyNoRelationName = ''
      this.principalOfSecondParty = ''
      this.principalOfSecondPartyMobile = ''
      this.formBaseData.payedCompanyName = ''
      this.formBaseData.depositBank = ''
      this.formBaseData.bankAccount = ''
      this.formBaseData.amount = ''
      this.formBaseData.orderDate = ''
      this.formBaseData.sectionIds = []
      this.formBaseData.memberUids = []
      this.formBaseData.secondParty = ''
      this.formBaseData.contractManageDeptName = ''
      this.formBaseData.title = ''
      this.formBaseData.changeAmount = ''
      this.formBaseData.principalOfSecondParty = ''
      this.formBaseData.principalOfSecondPartyMobile = ''
      this.formBaseData.initialPileNo = ''
      this.formBaseData.overPileNo = ''
      this.formBaseData.length = ''
      this.formBaseData.duration = ''
      if (this.formBaseData.type == '' || this.formBaseData.type == undefined) {
      } else {
        this.MContractType.forEach(item => {
          if (item.id == this.formBaseData.type) {
            this.contractTypeName = item.name
          }
        })
        this.getRelatedContractList(projectId, this.contractTypeName)
        this.getProjectSection(projectId)
      }
      if (this.formBaseData.type) {
        this.changeSelectType()
      }
    },
    /**
     * 更改合同类型
     *
     * */
    changeSelectType(callback) {
      if (!this.formBaseData.projectId) {
        this.$messageError('请先选择所属项目')
      } else {
        this.formBaseData.secondParty = ''
        this.MContractType.forEach(item => {
          if (item.id == this.formBaseData.type) {
            this.contractTypeName = item.name
          }
        })
        this.getRelatedContractList(this.formBaseData.projectId, this.contractTypeName)
        this.getProjectSection(this.formBaseData.projectId)

        if (this.contractTypeName == "监理合同") {
          this.selectList.companyListFiltered = this.selectList.companyList.filter(cp => cp.typeName && cp.typeName.indexOf("监理单位") != -1);

          this.secondCompanylabel = '选择监理单位'
          this.secondCompanyPersonlabel = '监理单位履约人员'
          this.formBaseRules.secondParty.forEach(item => {
            item.message = '请选择监理单位'
          })
          /*this.formBaseRules.memberUids.forEach(item=>{
            item.message='请选择监理单位履约人员'
          })*/
        }
        if (this.contractTypeName == "中心试验室合同") {
          this.selectList.companyListFiltered = this.selectList.companyList.filter(cp => cp.typeName && cp.typeName.indexOf("试验室单位") != -1);

          this.secondCompanylabel = '选择中心试验室单位'
          this.secondCompanyPersonlabel = '中心试验室履约人员'
          this.formBaseRules.secondParty.forEach(item => {
            item.message = '选择中心试验室单位'
          })
          /*this.formBaseRules.memberUids.forEach(item=>{
            item.message='请选择中心试验室履约人员'
          })*/
        }
        this.selectList.companyListFiltered.forEach((item) => {
          item.selectable = true
        })
      }
    },

    chooseSectionId() {
      if (!this.formBaseData.projectId) {
        this.$messageError('请先选择所属项目')
        return
      }
    },

    //选择关联合同
    chooseContract(contractId) {

      this.formBaseData.oldContractIdFlag = true
      // this.formBaseData.type = ''
      this.formBaseData.contractManaged = ''
      this.formBaseData.contractManageDeptName = ''
      // this.formBaseData.sectionIds = ''
      this.formBaseData.sectionIds = []
      this.formBaseData.number = ''
      this.formBaseData.numberName = ''
      this.formBaseData.title = ''
      this.formBaseData.amount = ''
      this.formBaseData.changeAmount = ''
      if (this.formBaseData.chooseIsConsortium == 1) {
        this.formBaseData.principalOfSecondParty = ''
        this.formBaseData.principalOfSecondPartyMobile = ''
        this.formBaseData.payedCompanyName = ''
        this.formBaseData.depositBank = ''
        this.formBaseData.bankAccount = ''
        this.formBaseData.orderDate = ''
      }
      this.selectList.contractList.forEach(item => {
        if (item.id == contractId) {

          this.formBaseData.contractManaged = item.contractManaged
          this.formBaseData.contractManageDeptName = item.contractManageDeptName

          this.formBaseData.number = item.number
          this.formBaseData.title = item.title
          this.formBaseData.amount = item.amount
          this.formBaseData.changeAmount = item.changeAmount


          if (this.formBaseData.chooseIsConsortium == 3) {
            this.formBaseData.principalOfSecondParty = item.principalOfSecondParty
            this.formBaseData.principalOfSecondPartyMobile = item.principalOfSecondPartyMobile
            this.formBaseData.payedCompanyName = item.payedCompanyName
            this.formBaseData.depositBank = item.depositBank
            this.formBaseData.bankAccount = item.bankAccount
            this.formBaseData.changeAmount = item.changeAmount
            this.formBaseData.orderDate = item.orderDate
          }
        }
      })


    },

    changeSecondParty() {//不是联合体时调用
      if (!this.formBaseData.projectId) {
        this.$messageError('请先选择所属项目')
        return
      }
      this.formBaseData.memberUids = []
      //this.getSecondPartUserTree()
      this.getLinkUserOpts(this.formBaseData.secondParty)
    },

    changeSecondPartyConsortium(id, index) {//是联合体时调用
      if (!this.formBaseData.projectId) {
        this.$messageError('请先选择所属项目')
        return
      }

      this.selectList.companyListFiltered.forEach(item => {
        if (item.id == this.formBaseData.consortiumGroup[index].secondParty) {
          item.selectable = false
        }
      })

      if (this.consortiumGroupCopy.length > 0) {
        this.selectList.companyListFiltered.forEach(item => {
          if (this.consortiumGroupCopy[index]) {
            if (this.consortiumGroupCopy[index].secondParty) {
              if ((item.id == this.consortiumGroupCopy[index].secondParty) &&
                (this.consortiumGroupCopy[index].secondParty != this.formBaseData.consortiumGroup[index].secondParty)) {
                item.selectable = true
              }
            }
          }
        })
      }

      this.formBaseData.consortiumGroup[index].memberUids = []
      //深拷贝
      var str = JSON.stringify(this.formBaseData.consortiumGroup);
      this.consortiumGroupCopy = JSON.parse(str);

      //this.getSecondPartUserTreeConsortium( index)
      this.getLinkUserOptsConsortium(index)
    },


    /**
     * 获取乙方单位参与人
     * */
    getSecondPartUserTree() {//不是联合体时调用
      mainline.getSecondPartUserTree(this.formBaseData.secondParty).then(res => {
        if (res.status === 1) {
          this.selectList.secondPartUserOpts = res.data
          this.$forceUpdate()
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(res => {
        console.log('请求出现错误', res);
        msgUtil.error2('获取履约人员列表失败!')
      })
    },

    /**
     * 获取乙方单位参与人
     * */
    getSecondPartUserTreeConsortium(index) {//是联合体时调用
      let chooseId = this.formBaseData.consortiumGroup[index].secondParty
      mainline.getSecondPartUserTree(chooseId).then(res => {
        if (res.status === 1) {
          this.formBaseData.consortiumGroup[index].secondPartUserOpts = res.data
          this.$forceUpdate()
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(res => {
        console.log('请求出现错误', res);
        msgUtil.error2('获取履约人员列表失败!')
      })
    },



    chooseConLabel(val) {
      return `选择${val}单位`
    },
    changeRadio() {
      if (this.formBaseData.chooseIsConsortium == 2) {
        this.formBaseData.consortiumNumber = '2'
      }
      if (this.formBaseData.chooseIsConsortium == 1) {
        if (this.formBaseData.secondParty.indexOf(",") != -1) {
          this.formBaseData.secondParty = ''
        }
        this.formBaseData.consortiumGroup = []
        this.formBaseData.mainlineContractDetailList = []
      }

      this.$forceUpdate()
    },
    setConNumber(val) {
      this.formBaseData.consortiumGroup.forEach((item, index) => {
        console.log(item, index)
        if (item.value == 1) {
          item.label = '牵头单位'
        } else {
          item.label = `成员${Number(item.value) - 1}`
        }
      })
    },
    changeConNumber(val) {
      console.log(val)
      let length = this.formBaseData.consortiumGroup.length

      if (length > 0) {
        //如果tab页已经存在值，及第二次change 下拉，
        let reduceNum = Number(val) - Number(length)
        if (reduceNum > 0) {
          console.log('增长')
          for (let i = 0; i < reduceNum; i++) {
            this.formBaseData.consortiumGroup.push({
              label: `成员${length + i}`,
              value: `${length + i + 1}`,
              secondParty: '',
              memberUids: '',
              principalOfSecondParty: '',
              constructionPeriodMoney: '',
              modifyConstructionPeriodMoney: '',
              defectsPeriodMoney: '',
              modifyDefectsPeriodMoney: '',
              provisionalSum: '',
              modifyProvisionalSum: '',
              principalOfSecondPartyMobile: '',
              payedCompanyName: '',
              depositBank: '',
              bankAccount: '',
              orderDate: '',
              rate: '',
              initialPileNo: '',
              overPileNo: '',
              length: '',
              duration: '',
            })
          }
        }
        if (reduceNum < 0) {
          console.log('缩短')
          //如果选择的数量 比之前的小
          // let arr = JSON.parse(JSON.stringify(this.formBaseData.consortiumGroup))
          this.formBaseData.consortiumGroup.splice(val, this.formBaseData.consortiumGroup.length - val)
          // this.$set(this.formBaseData,'consortiumGroup',arr)
          //缩短tab页之后 重置active下标
          this.consortiumActive = '1'

          //深拷贝
          var str = JSON.stringify(this.formBaseData.consortiumGroup);
          this.consortiumGroupCopy = JSON.parse(str);

          let secondParty = []
          this.consortiumGroupCopy.forEach((copy) => {
            secondParty.push(copy.secondParty)
          })
          this.selectList.companyListFiltered.forEach(item => {
            if (secondParty.indexOf(item.id) == -1) {
              item.selectable = true
            }
          })
        }
        this.$forceUpdate()

      } else {
        //如果tab 切换页长度为0 （初始） 进入
        let arr = [{
          label: '牵头单位',
          value: '1',
          secondParty: '',
          memberUids: '',
          principalOfSecondParty: '',
          constructionPeriodMoney: '',
          modifyConstructionPeriodMoney: '',
          defectsPeriodMoney: '',
          modifyDefectsPeriodMoney: '',
          provisionalSum: '',
          modifyProvisionalSum: '',
          principalOfSecondPartyMobile: '',
          payedCompanyName: '',
          depositBank: '',
          bankAccount: '',
          orderDate: '',
          rate: '',
          initialPileNo: '',
          overPileNo: '',
          length: '',
          duration: '',
        }]
        for (let i = 0; i < val - 1; i++) {
          arr.push({
            label: `成员${i + 1}`,
            value: `${i + 2}`,
            secondParty: '',
            memberUids: '',
            principalOfSecondParty: '',
            constructionPeriodMoney: '',
            modifyConstructionPeriodMoney: '',
            defectsPeriodMoney: '',
            modifyDefectsPeriodMoney: '',
            provisionalSum: '',
            modifyProvisionalSum: '',
            principalOfSecondPartyMobile: '',
            payedCompanyName: '',
            depositBank: '',
            bankAccount: '',
            orderDate: '',
            rate: '',
            initialPileNo: '',
            overPileNo: '',
            length: '',
            duration: '',
          })
        }
        this.$set(this.formBaseData, 'consortiumGroup', arr)
        this.$forceUpdate()
      }
      console.log(this.formBaseData.consortiumGroup, '================================')
    },


    blurInputEvent() {
      if (this.formBaseData.constructionPeriodMoney) {
        this.formBaseData.constructionPeriodMoney = Number(this.formBaseData.constructionPeriodMoney)
      }
      if (this.formBaseData.modifyConstructionPeriodMoney) {
        this.formBaseData.modifyConstructionPeriodMoney = Number(this.formBaseData.modifyConstructionPeriodMoney)
      }
      if (this.formBaseData.provisionalSum) {
        this.formBaseData.provisionalSum = Number(this.formBaseData.provisionalSum)
      }
      if (this.formBaseData.modifyProvisionalSum) {
        this.formBaseData.modifyProvisionalSum = Number(this.formBaseData.modifyProvisionalSum)
      }
      if (this.formBaseData.modifyDefectsPeriodMoney) {
        this.formBaseData.modifyDefectsPeriodMoney = Number(this.formBaseData.modifyDefectsPeriodMoney)
      }
      if (this.formBaseData.defectsPeriodMoney) {
        this.formBaseData.defectsPeriodMoney = Number(this.formBaseData.defectsPeriodMoney)
      }
      if (this.formBaseData.amount) {
        this.formBaseData.amount = Number(this.formBaseData.amount)
      }
      if (this.formBaseData.changeAmount) {
        this.formBaseData.changeAmount = Number(this.formBaseData.changeAmount)
      }
    }
    ,
    blurInputEvent_feilv(val) {
      if (this.formBaseData.chooseIsConsortium == 1) {
        if (this.formBaseData.rate) {
          this.formBaseData.rate = Number(this.formBaseData.rate).toFixed(2)
        }
      } else {
        if (val) {
          val = Number(val).toFixed(2)
        }
      }
    },

    // 获取详情请求 api
    getDetail() {
      mainline.getOne(this.detailId).then(res => {
        if (res.status == 1) {

          this.formBaseData = JSON.parse(JSON.stringify(res.data))
          this.formBaseData.sectionMutiSelect = true

          let sectionIds = res.data.sectionIdsJson
          this.formBaseData.type = res.data.type

          this.selectList.type.forEach((item) => {
            if (item.value == res.data.type) {
              this.contractTypeName = item.label
            }
          })
          if (this.contractTypeName == "监理合同") {
            this.selectList.companyListFiltered = this.selectList.companyList.filter(cp => cp.typeName && cp.typeName.indexOf("监理单位") != -1);
            this.secondCompanylabel = '选择监理单位'
            this.secondCompanyPersonlabel = '监理单位履约人员'
          }
          if (this.contractTypeName == "中心试验室合同") {
            this.selectList.companyListFiltered = this.selectList.companyList.filter(cp => cp.typeName && cp.typeName.indexOf("试验室单位") != -1);

            this.secondCompanylabel = '选择中心试验室单位'
            this.secondCompanyPersonlabel = '中心试验室履约人员'
          }
          this.formBaseData.consortiumNumber = String(res.data.coalitionNum)
          this.getScopeProjects(res.data.applyUser)
          this.getRelatedContractList(res.data.projectId, this.contractTypeName)
          this.getProjectSection(res.data.projectId)

          this.formBaseData.id = res.data.id
          this.formBaseData.sectionIds = sectionIds
          this.formBaseData.chooseIsConsortium = String(res.data.coalition)

          if (res.data.coalition == 1) {

            this.selectList.companyListFiltered.forEach((item) => {
              if (item.id == res.data.secondParty) {
                item.selectable = false
              } else {
                item.selectable = true
              }
            })

            let formBaseData = res.data;
            this.formBaseData.secondParty = res.data.secondParty

            let linkUsers = formBaseData.linkUsers
            this.formBaseData.linkUsers = linkUsers

            this.getLinkUserOptss(res.data.secondParty).then(res => {
              if (linkUsers) {
                let linkUserIds = formBaseData.linkUsers.split(',')
                let checkedLinkUsers = []
                for (let i = 0; i < linkUserIds.length; i++) {
                  let linkUser = this.linkUsers[linkUserIds[i]]
                  if (linkUser) {
                    checkedLinkUsers.push(linkUser)

                  }
                }
                this.$set(this, 'checkedLinkUsers', checkedLinkUsers)
                //this.checkedLinkUsers = checkedLinkUsers
              } else {
                this.$set(this, 'checkedLinkUsers', [])
                //this.checkedLinkUsers = []
              }
            })



            //this.getSecondPartUserTree()
            this.formBaseData.memberUids = res.data.memberUidsJson
          } else {
            if (this.formBaseData.mainlineContractDetailList) {
              let secondParty = []
              this.formBaseData.consortiumGroup = this.formBaseData.mainlineContractDetailList
              this.formBaseData.consortiumGroup.forEach((item, index) => {
                //this.getSecondPartUserTreeConsortium(index)
                //this.getLinkUserOptssConsortium(index)


                let linkUsers = item.linkUsers
                item.linkUsers = linkUsers

                this.getLinkUserOptssConsortium(index).then(res => {
                  if (linkUsers) {
                    let linkUserIds = item.linkUsers.split(',')
                    let checkedLinkUsers = []
                    for (let i = 0; i < linkUserIds.length; i++) {
                      let linkUser = this.linkUsers[linkUserIds[i]]
                      if (linkUser) {
                        checkedLinkUsers.push(linkUser)

                      }
                    }
                    this.$set(item, 'checkedLinkUsers', checkedLinkUsers)
                    //this.checkedLinkUsers = checkedLinkUsers
                  } else {
                    this.$set(item, 'checkedLinkUsers', [])
                    //this.checkedLinkUsers = []
                  }
                })



                secondParty.push(item.secondParty)
              })

              this.selectList.companyListFiltered.forEach(item => {
                if (secondParty.indexOf(item.id) == -1) {
                  item.selectable = true
                }
              })
              this.setConNumber(this.formBaseData.consortiumNumber)

              var str = JSON.stringify(this.formBaseData.consortiumGroup);
              this.consortiumGroupCopy = JSON.parse(str);

            }

          }

        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(() => {
        msgUtil.error2("获取详情信息失败")
      })
    }
    ,

    // 提交详情 提交1/暂存0 新建0/修改1
    submitDetail(type, callback) {
      this.formBaseData.id = this.detailId
      this.formBaseData.secondPartyRelation = true
      this.formBaseData.contractManaged = true
      this.formBaseData.mainlineContractType = 2
      this.formBaseData.mainlineContractDetailList = this.formBaseData.consortiumGroup
      //联合体情况下
      if (this.formBaseData.chooseIsConsortium == 2) {
        if (this.formBaseData.mainlineContractDetailList.length > 0) {
          this.formBaseData.mainlineContractDetailList.forEach((item, index) => {

            let linkUserIds = []
            let checkedLinkUsers = item.checkedLinkUsers
            if (checkedLinkUsers.length > 0) {
              for (let i = 0; i < checkedLinkUsers.length; i++) {
                linkUserIds.push(checkedLinkUsers[i].id)
              }
            }
            item.memberUids = linkUserIds
            item.linkUsers = linkUserIds.join(',')

          })
        }
      }
      if (this.formBaseData.chooseIsConsortium == 1) {
        //非联合体情况下
        let linkUserIds = []
        let checkedLinkUsers = this.checkedLinkUsers
        if (checkedLinkUsers.length > 0) {
          for (let i = 0; i < checkedLinkUsers.length; i++) {
            linkUserIds.push(checkedLinkUsers[i].id)
          }
        }
        this.formBaseData.memberUids = linkUserIds
        this.formBaseData.linkUsers = linkUserIds.join(',')
      }


      if (this.detailType === 'build') {
        mainline.submit(this.formBaseData).then(res => {
          if (res.status === 1) {
            this.detailId = res.data.id
            //this.saveFiles()
            //this.isLoading = false
            this.$notify({
              title: '数据修改成功',
              type: 'success',
              duration: 1500
            })
            this.saveFiles()
            // 传值给父组件刷新列表
            this.$emit('reloadList')
            this.formShow = false

          } else {
            msgUtil.error2(res.data.message)
          }
        }).catch((response) => {
          this.$notify({
            title: '数据表新增失败',
            type: 'error',
            duration: 2500
          })
        }).finally((response) => {
          this.isLoading = false
        })
      } else {
        mainline.resubmit(this.formBaseData).then(res => {
          if (res.status === 1) {
            this.detailId = res.data.id
            // this.saveFiles()
            //this.isLoading = false
            this.$notify({
              title: '数据修改成功',
              type: 'success',
              duration: 1500
            })
            this.saveFiles()
            // 传值给父组件刷新列表
            this.$emit('reloadList')
            this.formShow = false

          } else {
            msgUtil.error2(res.data.message)
          }
        }).catch((response) => {
          this.$notify({
            title: '数据表新增失败',
            type: 'error',
            duration: 2500
          })
        }).finally((response) => {
          this.isLoading = false
        })
      }

    },


    // 事件处理的api请求
    sealDealHttp(url, query, params, callback) {
      this.$httpPost(this.$store.state.httpHost.buss + url + query, params)
        .then((res) => {
          if (res.data.status === 1) {
            if (callback) callback(res.data)
          } else {
            this.$messageError(res.data.message)
          }
        })
        .catch((res) => {
          console.log('请求出现错误', res)
          console.log(res)
        })
    }
    ,
    // 点击各个流程的按钮事件
    handleClickDeal(type, res) {
      console.log(type, res)
      switch (type) {
        // 取消，关闭窗口
        case 'cancel':
          // 重置表单验证
          if (this.$refs['formBaseData']) {
            this.$refs['formBaseData'].resetFields()
          }
          //清空表单内容
          this.formBaseData = {
            chooseIsConsortium: '1',
            consortiumGroup: [],
            oldContractId: '',
            oldContractIdFlag: false,
            consortiumNumber: '',
            memberUids: [],
            secondPartyRelation: true,
            // enableSectionSelection:false,
            sectionIds: '',
            contractManaged: false,
            sectionMutiSelect: true,
            //合同信息
            number: '',
            numberName: '',
            title: '',
            amount: '',
            changeAmount: '',
            type: '',
            secondParty: '',
            rate: '',
            initialPileNo: '',
            length: '',
            principalOfSecondParty: '',
            principalOfSecondPartyMobile: '',
            payedCompanyName: '',
            depositBank: '',
            bankAccount: '',
            contractManageDeptName: '',
            overPileNo: '',
            duration: '',
            orderDate: '',
            modifyProvisionalSum: '',
            provisionalSum: '',
            constructionPeriodMoney: '',
            modifyConstructionPeriodMoney: '',
            defectsPeriodMoney: '',
            modifyDefectsPeriodMoney: '',
          } // 表单基本信息内容
          // 清空文件
          this.selectList.file = []
          this.contractTypeName = ''
          this.selectList.type = []
          this.selectList.companyList = []
          this.selectList.scopeProjects = []
          this.selectList.contractList = []
          this.selectList.sectionList = []
          this.MContractType = []
          this.selectList.companyListFiltered = []
          this.selectList.secondPartUserOpts = []
          this.buildUnitTable = []
          // 关闭弹窗
          this.formShow = false
          this.enableSectionSelection = false
          this.enableWhetherManageSelection = false
          this.detailId = ''
          this.checkedLinkUsers = []
          break
        // 保存
        case 'submit':
          let flag = res.flag
          // 表单验证
          this.$refs['formBaseData'].validate((valid) => {
            if (valid) {
              this.isLoading = true
              // 提交详情
              this.submitDetail(flag, () => {
                this.saveFiles()
              })
            } else {
              this.isLoading = false
            }
          })
          break
        // 删除

      }
    },

    saveFiles() {
      this.$refs['cmsFileTable'].bindAllFile(this.detailId)
    },


    handleClick(name, action) {
    },


    /**
     *显示删除按钮
     * @param row
     */
    buttonDelShow(row) {
      let flag = false
      if ((this.detailType === 'build' || this.detailType === 'edit') && row.file[0].realName !== '' && !row.isNeed) {
        flag = true
      }
      // 经办人操作时
      // if ((this.detailType!=='build'&&this.detailType!=='edit'&&this.detailType!=='check')&&this.isReport&&row.file[0].realName!==''&&!row.isNeed) {
      //   flag=true
      // }
      // 多文件上传的控制的控制
      if (row.isMulti) {
        flag = false
      }
      return flag;
    },
    /**
     *控制显示暂无文件
     * @param row
     */
    showNone(row) {
      let flag = false
      if ((this.detailType !== 'build' && this.detailType !== 'edit') && row.file[0].realName === '') {
        flag = true
      }
      // 经办人操作时
      // if ((this.detailType!=='build'&&this.detailType!=='edit'&&this.detailType!=='check')&&this.isReport) {
      //   flag=false
      // }
      return flag
    },
    /**
     * 控制查看按钮显示
     * @param row
     */
    buttonCheckShow(row) {
      let flag = false
      if ((this.detailType !== 'build' && this.detailType !== 'edit') && row.file[0].realName !== '') {
        flag = true
      }
      // 经办人操作时
      // if ((this.detailType!=='build'&&this.detailType!=='edit'&&this.detailType!=='check')&&this.isReport) {
      //   flag=false
      // }
      // 多文件上传的控制的控制
      if (row.isMulti) {
        flag = false
      }
      return flag
    },
    /**
     * 控制上传按钮显示
     * @param row
     * @returns {boolean}
     */
    buttonUploadShow(row) {
      let flag = false
      if (this.detailType === 'build' || this.detailType === 'edit') {
        flag = true
      }
      // 经办人操作时
      // if ((this.detailType!=='build'&&this.detailType!=='edit'&&this.detailType!=='check')&&this.isReport) {
      //   flag=true
      // }
      return flag
    },
    tableChange(val) {
      this.$set(this, 'buildUnitTable', [...val])
    },

  }
}
</script>

<style scoped lang="scss">
.el-select.half {
  width: 250px;
}

.el-select.fill {
  width: 800px;
}

.contract_input {
  width: 250px;
}

.contract_input2 {
  width: 240px;
}

.el-input .el-select {
  width: 130px;
}

.fee_add {
  color: #008fe0;
  border-color: #008fe0;
  float: right;
  margin-bottom: 10px;
}
</style>
